import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import {
  List,
  Card,
  Tag,
  Button,
  Select,
  Typography,
  Modal,
  Form,
  Input,
  InputNumber,
  message,
  Spin,
  Popconfirm,
  DatePicker,
} from "antd";
import {
  PlusOutlined,
  GiftOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import "./style.styl";
import dayjs from "dayjs";
import {getAuthToken} from "@/router/index.jsx";

const { Title } = Typography;
const { TextArea } = Input;
const { Option } = Select;

// 创建axios实例
const api = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 10000,
});

// 设置请求拦截器
api.interceptors.request.use(config => {
  config.headers.Authorization = `${getAuthToken()}`
  return config
})

// 设置响应拦截器
api.interceptors.response.use(
    response => {
      // 直接返回整个响应体
      return response;
    },
    error => {
      if (error.response) {
        const { status, data } = error.response;

        // 处理401未授权错误
        if (status === 401) {
          localStorage.removeItem("access_token");
          window.location.href = "/login?redirect=" + encodeURIComponent(window.location.pathname);

          return Promise.reject({
            code: 401,
            message: "会话已过期，请重新登录"
          });
        }

        // 返回统一的错误格式
        return Promise.reject({
          code: data.code || status,
          message: data.message || "请求失败"
        });
      } else {
        return Promise.reject({
          code: -1,
          message: "网络错误，请检查网络连接"
        });
      }
    }
);


const BountyListContent = () => {
  const [bounties, setBounties] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState({
    status: "all",
    sort: "newest",
  });
  const [currentUser, setCurrentUser] = useState(null);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      const response = await api.get("/api/user/info");
      setCurrentUser(response);
    } catch (error) {
      console.error("获取用户信息失败:", error);
      message.error(error.message || "获取用户信息失败");
    }
  };

  // 获取悬赏任务列表
  const getBountyList = async (params) => {
    try {
      const res = await api.get("/api/bounty-tasks", {
        params: {
          page: params.page,
          size: params.size,
          status: params.status !== "all" ? params.status : undefined,
          sort: params.sort,
        }
      });
      return res.data; // 直接返回data字段
    } catch (error) {
      throw error;
    }
  };


  // 创建悬赏任务
  const createBounty = async (values) => {
    try {
      const res = await api.post("/api/bounty-tasks", values);
      return res; // 返回完整的响应
    } catch (error) {
      throw error;
    }
  };

  // 关闭悬赏任务
  const closeBounty = async (taskId) => {
    try {
      const res = await api.post(`/api/bounty-tasks/${taskId}/close`);
      return res; // 返回完整的响应
    } catch (error) {
      throw error;
    }
  };

  // 加载悬赏任务数据
  const loadBounties = async (page = 1, filters = {}) => {
    setLoading(true);
    try {
      // 调用API获取数据
      const res = await getBountyList({
        page,
        size: pagination.pageSize,
        ...filters,
      });
      console.log("API响应:", res);
      // 直接使用接口返回的数据结构
      setBounties(res.data.tasks || []);
      setPagination({
        ...pagination,
        current: res.data.currentPage || page,
        pageSize: res.data.pageSize || pagination.pageSize,
        total: res.data.total || 0,
      });
    } catch (error) {
      console.error("加载悬赏任务失败:", error);
      message.error(error.message || "加载悬赏任务失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCurrentUser();
  }, []);

  useEffect(() => {
    if (currentUser) {
      loadBounties(pagination.current, filters);
    }
  }, [filters, currentUser]);

  const handlePageChange = (page) => {
    loadBounties(page, filters);
  };

  const handleFilterChange = (name, value) => {
    setFilters({ ...filters, [name]: value });
  };

  const openCreateModal = () => {
    if (!currentUser) {
      message.warning('请先登录');
      navigate('/login');
      return;
    }

    setModalVisible(true);
    form.resetFields();
  };

  const handleCreateBounty = async (values) => {
    setSubmitting(true);
    try {
      const params = {
        title: values.title,
        description: values.description,
        rewardMagic: values.reward,
        deadline: values.deadline ? values.deadline.format('YYYY-MM-DDTHH:mm:ss') : null
      };

      await createBounty(params);
      message.success("悬赏任务发布成功");
      setModalVisible(false);
      loadBounties(1, filters);
    } catch (error) {
      console.error("发布悬赏任务失败:", error);

      // 处理特定错误码
      if (error.code === 1006) {
        message.error("分享率过低，无法下载新种子");
      } else if (error.code === 400) {
        message.error("请求参数错误");
      } else {
        message.error(error.message || "发布失败，请稍后重试");
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleCloseBounty = async (id, e) => {
    e.stopPropagation();
    try {
      await closeBounty(id);
      message.success("悬赏任务已关闭");
      loadBounties(pagination.current, filters);
    } catch (error) {
      console.error("关闭悬赏任务失败:", error);

      // 处理特定错误码
      if (error.code === 403) {
        message.error("无权限执行此操作");
      } else {
        message.error(error.message || "关闭失败，请稍后重试");
      }
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case "active": return "green";
      case "completed": return "blue";
      case "expired": return "red";
      case "closed": return "gray";
      default: return "default";
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case "active": return "进行中";
      case "completed": return "已完成";
      case "expired": return "已过期";
      case "closed": return "已关闭";
      default: return "未知状态";
    }
  };

  // 判断用户是否是发布者
  const isPublisher = (publisherId) => {
    return currentUser && publisherId === currentUser.id;
  };

  // 判断任务是否可关闭
  const canClose = (status) => {
    return status === "active" || status === "expired";
  };

  return (
      <div className="bounty-list-container">
        <div className="bounty-header">
          <Title level={2}>资源悬赏</Title>
          <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={openCreateModal}
              className="publish-button"
          >
            发布资源悬赏
          </Button>
        </div>

        <div className="filter-bar">
          <span className="filter-label">状态：</span>
          <Select
              defaultValue="all"
              style={{ width: 120 }}
              onChange={(value) => handleFilterChange("status", value)}
          >
            <Option value="all">全部</Option>
            <Option value="active">进行中</Option>
            <Option value="completed">已完成</Option>
            <Option value="expired">已过期</Option>
            <Option value="closed">已关闭</Option>
          </Select>

          <span className="filter-label">排序：</span>
          <Select
              defaultValue="newest"
              style={{ width: 150 }}
              onChange={(value) => handleFilterChange("sort", value)}
          >
            <Option value="newest">最新发布</Option>
            <Option value="reward_desc">奖励从高到低</Option>
            <Option value="reward_asc">奖励从低到高</Option>
          </Select>
        </div>

        {loading ? (
            <div className="loading-container">
              <Spin size="large" tip="数据加载中..." />
            </div>
        ) : (
            <List
                className="bounty-list"
                grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }}
                dataSource={bounties}
                pagination={{
                  onChange: handlePageChange,
                  current: pagination.current,
                  pageSize: pagination.pageSize,
                  total: pagination.total,
                  showTotal: (total) => `共 ${total} 个悬赏`,
                  showSizeChanger: false,
                }}
                renderItem={(item) => (
                    <List.Item>
                      <Card
                          hoverable
                          className="bounty-card"
                          onClick={() => navigate(`/community/bounty/${item.id}`)}
                          actions={
                            isPublisher(item.publisherId) && canClose(item.status)
                                ? [
                                  <Popconfirm
                                      title="确定要关闭此悬赏任务吗？关闭后将返还魔力值"
                                      onConfirm={(e) => handleCloseBounty(item.id, e)}
                                      onCancel={(e) => e.stopPropagation()}
                                      okText="确认"
                                      cancelText="取消"
                                  >
                                    <CloseOutlined
                                        onClick={(e) => e.stopPropagation()}
                                        key="close"
                                    />
                                  </Popconfirm>,
                                ]
                                : []
                          }
                      >
                        <div className="bounty-card-header">
                          <Tag color={getStatusColor(item.status)}>
                            {getStatusText(item.status)}
                          </Tag>
                          <div className="bounty-reward">
                            <GiftOutlined /> {item.rewardMagic} 魔力值
                          </div>
                        </div>
                        <Title level={4} className="bounty-title">
                          {item.title}
                        </Title>
                        <div className="bounty-info">
                          <div className="bounty-publisher">
                            发布者: {item.publisherName}
                          </div>
                          <div className="bounty-date">
                            {dayjs(item.createdAt).format("YYYY-MM-DD")}
                          </div>
                          {item.deadline && (
                              <div className="bounty-deadline">
                                截止: {dayjs(item.deadline).format("YYYY-MM-DD")}
                              </div>
                          )}
                        </div>
                      </Card>
                    </List.Item>
                )}
            />
        )}

        <Modal
            title="发布资源悬赏"
            open={modalVisible}
            onCancel={() => setModalVisible(false)}
            footer={null}
            width={600}
            destroyOnClose
        >
          <Form form={form} layout="vertical" onFinish={handleCreateBounty}>
            <Form.Item
                name="title"
                label="悬赏标题"
                rules={[
                  { required: true, message: '请输入悬赏标题' },
                  { max: 50, message: '标题不能超过50个字符' },
                ]}
            >
              <Input placeholder="请输入悬赏标题" maxLength={50} showCount />
            </Form.Item>

            <Form.Item
                name="description"
                label="需求描述"
                rules={[
                  { required: true, message: '请输入需求描述' },
                  { max: 500, message: '描述不能超过500个字符' },
                ]}
            >
              <TextArea
                  placeholder="请详细描述您的资源需求..."
                  rows={6}
                  maxLength={500}
                  showCount
              />
            </Form.Item>

            <Form.Item
                name="reward"
                label="奖励魔力值"
                rules={[
                  { required: true, message: '请输入奖励魔力值' },
                  {
                    type: 'number',
                    min: 100,
                    max: 10000,
                    message: '奖励范围为100-10000',
                  },
                ]}
            >
              <InputNumber
                  placeholder="最小100，最大10000"
                  style={{ width: '100%' }}
                  min={100}
                  max={10000}
              />
            </Form.Item>

            <Form.Item
                name="deadline"
                label="截止日期（可选）"
            >
              <DatePicker
                  style={{ width: '100%' }}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  disabledDate={(current) => {
                    return current && current < dayjs().startOf('day');
                  }}
              />
            </Form.Item>

            <div className="form-actions">
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button
                  type="primary"
                  htmlType="submit"
                  loading={submitting}
                  disabled={!currentUser}
              >
                {currentUser ? '发布悬赏' : '请先登录'}
              </Button>
            </div>
          </Form>
        </Modal>
      </div>
  );
};

export default BountyListContent;